<template>
  <el-card>
    <el-row justify="space-between">
      <el-col :span="8">
        <!-- 搜索条件输入框，按回车键搜索（注意，clearable和clear事件必须一起设置） -->
        <el-input
          v-model="searchParams.name"
          style="width: 240px"
          placeholder="请输入分类名称"
          :prefix-icon="Search"
          clearable
          @keyup.enter="goSearch"
          @clear="goSearch"
        />
      </el-col>
      <el-col :span="8" style="text-align: right">
        <!-- 新增分类按钮，按此按钮打开对话框 -->
        <el-button type="primary" @click="addCategory()"> + 新增分类 </el-button>
      </el-col>
    </el-row>
    <!-- 以下是展示分类的表格 -->
    <el-row>
      <el-col>
        <el-table :data="categoryList" style="width: 100%">
          <el-table-column
            label="分类名称"
            width="200"
            align="center"
            prop="name"
          ></el-table-column>
          <el-table-column prop="type" label="分类类型" align="center">
            <template v-slot="scope">
              <el-tag :type="scope.row.type == '1' ? 'primary' : 'success'">{{
                scope.row.type == '1' ? '菜品' : '套餐'
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="操作时间" align="center">
            <template #default="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180px">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                修改
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 以下是分页组件 -->
    <el-row>
      <el-col>
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </el-card>

  <!-- 新增、编辑套餐分类 -->
  <el-dialog v-model="cateDialogVisible" :title="cateDialogTitle" width="500">
    <el-form :model="cateForm" label-width="100px">
      <el-form-item label="分类名称">
        <el-input v-model="cateForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="cateForm.type">
          <el-option label="菜品" :value="1" />
          <el-option label="套餐" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="cateForm.sort" type="number" placeholder="请输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm()"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { onMounted } from 'vue'
import {
  reqGetCategoryList,
  reqAddCategory,
  reqEditCategory,
  reqDeleteCategory
} from '@/api/category'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

onMounted(() => {
  getCategoryList()
})

//分页+条件搜索
const searchParams = ref({
  page: 1,
  pageSize: 10, //默认是10
  name: '' //菜品或套餐的分类名称
})

// 渲染表格中列表数据
const categoryList = ref([])
const total = ref(0) //总记录条数

const getCategoryList = async () => {
  const res = await reqGetCategoryList(searchParams.value)
  console.log(res)
  categoryList.value = res.data.data.records
  total.value = res.data.data.total
}

const goSearch = () => {
  getCategoryList()
}

//分页逻辑
const handleSizeChange = () => {
  getCategoryList()
}
const handleCurrentChange = () => {
  getCategoryList()
}

//新增分类功能的逻辑
const cateDialogTitle = ref('添加菜品/套餐分类') //对话框的标题
const cateDialogVisible = ref(false) //控制对话框是否显示
const action = ref('add') // 控制当前是新增？修改？
//分类表单
const cateForm = ref({
  categoryId: '',
  name: '',
  sort: 0,
  type: 1 //类型-1 菜品分类（默认） -2 套餐分类
})

//给“新增分类”按钮，绑定事件，控制对话框的显示
const addCategory = () => {
  cateDialogTitle.value = '添加菜品/套餐分类'
  action.value = 'add'
  cateForm.value.name = ''
  cateForm.value.categoryId = ''
  cateForm.value.sort = 0
  cateDialogVisible.value = true
}
//提交表单
const submitForm = async () => {
  if (action.value === 'add') {
    //新增操作
    await reqAddCategory(cateForm.value)
    ElMessage({
      message: '分类添加成功',
      type: 'success'
    })
  } else {
    //修改操作
    await reqEditCategory(cateForm.value)
    ElMessage({
      message: '分类修改成功',
      type: 'success'
    })
  }

  getCategoryList()
  cateDialogVisible.value = false
}

//编辑分类
const handleEdit = (row) => {
  console.log(row)
  //回显数据
  cateForm.value = { ...row }
  cateDialogVisible.value = true
  action.value = 'edit'
}

// 删除分类
const handleDelete = (cate) => {
  console.log(cate.id)
  ElMessageBox.confirm(`确定要删除[${cate.name}]分类?`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: '警告'
  })
    .then(async () => {
      await reqDeleteCategory(cate.id)
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      getCategoryList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
</style>
